﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SkypeTranslater.Outlook
{
	public sealed class OutlookItem
	{
		public string FromEmail { get; set; }
		public string FromLanguage { get; set; }
		public string ToLanguage { get; set; }

		public override bool Equals(object obj)
		{
			if (obj == null)
				return false;

			if (object.ReferenceEquals(this, obj))
				return true;

			if (!(obj is OutlookItem))
				return false;

			OutlookItem comp = (obj as OutlookItem);

			return (string.Compare(this.FromEmail, comp.FromEmail, true) == 0 &&
					string.Compare(this.FromLanguage, comp.FromLanguage, true) == 0 &&
					string.Compare(this.ToLanguage, comp.ToLanguage, true) == 0);
		}

		public override string ToString()
		{
			return string.Format("{0}  {1}-{2}", this.FromEmail, this.FromLanguage, this.ToLanguage);
		}
	}

	public class OutlookItemCollection
	{
		public List<OutlookItem> m_data = null;

		public OutlookItemCollection()
		{
			m_data = new List<OutlookItem>();
		}

		public void Add(OutlookItem item)
		{
			throwExc(item);
			if (!m_data.Contains(item))
				m_data.Add(item);
		}

		public void Remove(OutlookItem item)
		{
			throwExc(item);
			if (m_data.Contains(item))
				m_data.Remove(item);
		}

		public void Load(string pathToFile)
		{
			if (!System.IO.File.Exists(pathToFile))
				throw new System.IO.FileNotFoundException("File not found", pathToFile);

			XDocument doc = XDocument.Load(pathToFile);
			m_data.Clear();

			foreach (XElement item in doc.Element("Groups").Element("Outlook").Elements("Item"))
			{
				OutlookItem mail = new OutlookItem();
				mail.ToLanguage = item.Element("ToLanguage").Value;
				mail.FromLanguage = item.Element("FromLanguage").Value;
				mail.FromEmail = item.Element("Sender").Value;
				m_data.Add(mail);
			}
		}

		public void Save(string pathToFile)
		{
			if (System.IO.File.Exists(pathToFile))
				throw new System.IO.FileNotFoundException("File not found", pathToFile);

			XDocument doc = XDocument.Load(pathToFile);
			m_data.Clear();

			XElement outlook = doc.Element("Groups").Element("Outlook");
			outlook.RemoveNodes();

			foreach (OutlookItem mail in m_data)
			{
				XElement element = new XElement("Item", new XElement("Sender", mail.FromEmail),
					new XElement("FromLanguage", mail.FromLanguage), new XElement("ToLanguage", mail.ToLanguage));
				outlook.Add(element);
			}

			doc.Save(pathToFile);
		}

		private static void throwExc(OutlookItem item)
		{
			if (item == null) throw new ArgumentNullException("item", "item connot be null");
		}
	}
}
